/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.campaign.service.impl.CampaignServiceImpl
   Module Description   :

   Date Created      : 2009/11/18
   Original Author   : eric.chen
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.campaign.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.hibernate.Hibernate;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.service.impl.DomainServiceImpl;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.mail.entity.Mail;
import com.yaodian100.core.mail.service.MailService;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.core.menu.service.MenuService;
import com.yaodian100.core.template.service.TemplateService;
import com.yaodian100.ec.campaign.entity.Campaign;
import com.yaodian100.ec.campaign.entity.CampaignExtend;
import com.yaodian100.ec.campaign.entity.Campaign.Type;
import com.yaodian100.ec.campaign.service.CampaignService;
import com.yaodian100.ec.category.entity.Category;
import com.yaodian100.ec.category.service.CategoryService;
import com.yaodian100.ec.member.service.MemberService;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.entity.SpecificationInventory;
import com.yaodian100.ec.product.service.ProductService;

/**
 * @author eric.chen
 * 
 */
public class CampaignServiceImpl extends DomainServiceImpl<Campaign> implements CampaignService {

	private String checkDate = "99999";
	private List<Campaign> activeCampaigns = new ArrayList();
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private TemplateService templateService;
	@Autowired
	private ProductService productService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private MailService mailService;
	@Autowired
	private BaseManager baseMgr;
	@Autowired
	private MenuService menuService;

	// @Autowired
	// private UserService userService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.core.common.service.impl.DomainServiceImpl#get(java.io.Serializable)
	 */
	@Override
	public Campaign get(Serializable oid) throws CoreException {
		Campaign entity = super.get(oid);
		// if (!Arrays.asList(Type.M02, Type.M03).contains(entity.getType())) {
		Hibernate.initialize(entity.getTypeExtends());
		// }
		return entity;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.core.common.service.impl.DomainServiceImpl#delete(java.lang.Object)
	 */
	@Override
	@Transactional(readOnly = false)
	public void delete(Campaign entity) throws CoreException {
		entity.setDelete(true);
		getDao().update(entity);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.core.common.service.impl.DomainServiceImpl#getList(int, int,
	 * com.yaodian100.core.common.dao.impl.CommonCriteria, java.lang.String[])
	 */
	@Override
	public List<Campaign> getList(int firstResult, int maxResults, CommonCriteria criteria, String[] sortOrder)
			throws CoreException {
		if (criteria == null) {
			criteria = new CommonCriteria();
		}
		criteria.addEq("delete", false);
		List<Campaign> campaignList = super.getList(firstResult, maxResults, criteria, sortOrder);
		for (Campaign entity : campaignList) {
			// if (!Arrays.asList(Type.M02, Type.M03).contains(entity.getType())) {
			Hibernate.initialize(entity.getTypeExtends());
			// }
		}
		return campaignList;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seecom.yaodian100.core.common.service.impl.DomainServiceImpl#getListSize(com.yaodian100.core.common.dao.impl.
	 * CommonCriteria)
	 */
	@Override
	public Number getListSize(CommonCriteria criteria) throws CoreException {
		if (criteria == null) {
			criteria = new CommonCriteria();
		}
		criteria.addEq("delete", false);
		return super.getListSize(criteria);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.core.common.service.impl.DomainServiceImpl#getAll(int, int, java.lang.String[])
	 */
	@Override
	public List<Campaign> getAll(int firstResult, int maxResults, String[] sortOrder) throws CoreException {
		CommonCriteria criteria = new CommonCriteria();
		criteria.addEq("delete", false);
		return getList(0, -1, criteria, sortOrder);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.core.common.service.impl.DomainServiceImpl#getAllSize()
	 */
	@Override
	public Number getAllSize() throws CoreException {
		CommonCriteria criteria = new CommonCriteria();
		criteria.addEq("delete", false);
		return getListSize(criteria);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.campaign.service.CampaignService#getValidCampaign(java.lang.String)
	 */
	@Override
	public List<Campaign> getValidCampaign(String categoryPath, String productId, Map options) throws CoreException {
		Date now = DateUtil.getCurrentTime();
		String nowString = DateUtil.convertDateToString("ddHHmm", now);
		if (!nowString.startsWith(checkDate)) {
			CommonCriteria cri = new CommonCriteria();
			cri.addEq("enable", true);
			cri.addGe("endDateTime", now);
			cri.addLe("startDateTime", now);
			cri.addIn("type", Arrays.asList(Type.C01, Type.C02, Type.C03, Type.S01, Type.S02));
			activeCampaigns = getList(0, -1, cri, null);
			logger.info("renew activeCampaigns:{}", activeCampaigns);
			// 取前五碼, 每 10min 更新一次
			checkDate = DateUtil.convertDateToString("ddHHmm", now).substring(0, 5);
		}
		return getValidCampaignByObj(categoryPath, productId, options, activeCampaigns);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.campaign.service.CampaignService#getValidCampaign(java.lang.String, java.util.List)
	 */
	@Override
	public List<Campaign> getValidCampaign(String categoryPath, String productId, Map options, List<String> campaigns)
			throws CoreException {
		// 取得 memory cache 中的 activeCampaigns 以便比对, 减轻 db loading
		List<Campaign> checkCampaigns = new ArrayList<Campaign>(activeCampaigns);
		List<String> checkCampaignIds = new ArrayList();
		for (Campaign campaignObj : checkCampaigns) {
			checkCampaignIds.add(campaignObj.getUuid());
		}
		boolean check = true;
		for (String c : campaigns) {
			if (!checkCampaignIds.contains(c)) {
				// 传入的 campaigns 有不存在 activeCampaigns 的活动. 原因可能是换档活动失效. 使用资料库查询有效活动
				check = false;
				break;
			}
		}
		if (!check) {
			// 若 check = false, 把活动 end date 延迟五分钟由资料库捞取
			Calendar date = Calendar.getInstance();
			date.setTime(DateUtil.getCurrentTime());
			CommonCriteria cri = new CommonCriteria();
			cri.addIn("uuid", campaigns);
			cri.addEq("enable", true);
			cri.addLe("startDateTime", date.getTime());
			date.add(Calendar.MINUTE, -5);
			cri.addGe("endDateTime", date.getTime());
			cri.addIn("type", Arrays.asList(Type.C01, Type.C02, Type.C03, Type.S01, Type.S02));
			checkCampaigns = getList(0, -1, cri, null);
		}
		return getValidCampaignByObj(categoryPath, productId, options, checkCampaigns);
	}

	/**
	 * @param categoryPath
	 * @param productId
	 * @param option
	 * @param campaigns
	 * @return
	 */
	private List<Campaign> getValidCampaignByObj(String categoryPath, String productId, Map<String, String> option,
			List<Campaign> campaigns) {
		String cookie = "", domain = "", memberId = "";
		if (option != null) {
			cookie = StringUtils.defaultIfEmpty(option.get("cookie"), "yaodian100");
			domain = StringUtils.defaultIfEmpty(option.get("domain"), ServerValue.getFrontHostname().substring(7));
			memberId = StringUtils.defaultIfEmpty(option.get("memberId"), "");
		} else {
			cookie = "yaodian100";
			domain = ServerValue.getFrontHostname().substring(7);
		}

		if (StringUtils.isNotBlank(categoryPath)) {
			// categoryPath 可能被維護為 categoryId, 嘗試轉換為 categoryPath
			if (NumberUtils.isNumber(categoryPath)) {
				Category category = categoryService.get(Long.valueOf(categoryPath));
				categoryPath = category.getCategoryPath();
			}
			// categoryPath 增加 '/' 避免誤判 9/102 與 9/103 都符合 9/10
			categoryPath = categoryPath + "/";
		}
		List<Campaign> result = new ArrayList<Campaign>();
		for (Campaign c : campaigns) {
			if (Arrays.asList(Type.C01.getCode(), Type.C02.getCode(), Type.C03.getCode(), Type.S01.getCode(),
					Type.S02.getCode()).contains(c.getType().getCode())) {
				if (domain.equals(c.getDomain()) && (StringUtils.isBlank(c.getCookie()) || c.getCookieArray().contains(cookie))) {
					boolean isValid = false;
					if (Campaign.Range.Order.equals(c.getRange())) {
						isValid = true;
					} else if (Campaign.Range.Category.equals(c.getRange())
							|| Campaign.Range.RedGreenCategory.equals(c.getRange())) {
						if (c.getRangeExt() != null && StringUtils.isNotBlank(categoryPath)) {
							for (String cp : StringUtils.split(c.getRangeExt(), ",")) {
								// cp 應該為 1/123 or 1/23/456 .. 等
								if (categoryPath.startsWith(cp + "/")) {
									// cp 增加 '/' 避免誤判 9/102 與 9/103 都符合 9/10
									isValid = true;
								}
							}
						}
					} else if (Campaign.Range.Product.equals(c.getRange())) {
						for (String s : c.getRangeExtIds()) {
							if (s.equals(productId)) {
								isValid = true;
							}
						}
					} else {
						throw new CoreException("errors.campaign.type", c.getUuid(), c.getType().getCode());
					}
					if (isValid && StringUtils.isNotBlank(c.getCheckScript())) {
						Map objs = new HashMap();
						if (StringUtils.isNotBlank(productId)) {
							objs.put("product", productService.get(productId));
						}
						if (StringUtils.isNotBlank(memberId)) {
							objs.put("member", memberService.get(memberId));
						}
						String scriptResult = templateService.formatByStringTemplate(c.getCheckScript(), objs);
						if (StringUtils.contains(scriptResult, "true")) {
							result.add(c);
						}
					} else if (isValid && StringUtils.isBlank(c.getCheckScript())) {
						result.add(c);
					}
				}
			}
		}
		return result;
	}

	/**
	 * @param categoryPath
	 * @param productId
	 * @param option
	 * @param campaigns
	 * @return
	 */
	private List<Campaign> getValidCampaignTypeByObj(String categoryPath, String productId, Map<String, String> option,
			List<Campaign> campaigns) {
		String cookie = "", domain = "", memberId = "";
		if (option != null) {
			cookie = StringUtils.defaultIfEmpty(option.get("cookie"), "yaodian100");
			domain = StringUtils.defaultIfEmpty(option.get("domain"), ServerValue.getFrontHostname().substring(7));
			memberId = StringUtils.defaultIfEmpty(option.get("memberId"), "");
		} else {
			cookie = "yaodian100";
			domain = ServerValue.getFrontHostname().substring(7);
		}

		if (StringUtils.isNotBlank(categoryPath)) {
			// categoryPath 可能被維護為 categoryId, 嘗試轉換為 categoryPath
			if (NumberUtils.isNumber(categoryPath)) {
				Category category = categoryService.get(Long.valueOf(categoryPath));
				categoryPath = category.getCategoryPath();
			}
			// categoryPath 增加 '/' 避免誤判 9/102 與 9/103 都符合 9/10
			categoryPath = categoryPath + "/";
		}

		List<Campaign> result = new ArrayList<Campaign>();
		for (Campaign c : campaigns) {
			if (domain.equals(c.getDomain()) && (StringUtils.isBlank(c.getCookie()) || c.getCookieArray().contains(cookie))) {
				boolean isValid = false;
				if (Campaign.Range.Order.equals(c.getRange())) {
					isValid = true;
				} else if (Campaign.Range.Category.equals(c.getRange())) {
					if (c.getRangeExt() != null && StringUtils.isNotBlank(categoryPath)) {
						for (String cp : StringUtils.split(c.getRangeExt(), ",")) {
							// cp 應該為 1/123 or 1/23/456 .. 等
							if (categoryPath.startsWith(cp + "/")) {
								// cp 增加 '/' 避免誤判 9/102 與 9/103 都符合 9/10
								isValid = true;
							}
						}
					}
				} else if (Campaign.Range.Product.equals(c.getRange())) {
					for (String s : c.getRangeExtIds()) {
						if (s.equals(productId)) {
							isValid = true;
						}
					}
				} else {
					throw new CoreException("errors.campaign.type", c.getUuid(), c.getType().getCode());
				}
				if (isValid) {
					result.add(c);
				}
			}
		}
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.campaign.service.CampaignService#sendCampaignStockEmail()
	 */
	@Override
	@Transactional(readOnly = false)
	public boolean sendCampaignStockEmail(String domainName) throws CoreException {
		try {
			Map<String, String> options = new HashMap<String, String>();
			options.put("domain", domainName);
			List<Campaign> campaigns = getValidCampaign("", "", options);
			// send mail
			Map<Object, Object> objs = null;
			for (Campaign campaign : campaigns) {
				if (campaign.getType().equals(Campaign.Type.C03)) {
					for (CampaignExtend extend : campaign.getTypeExtends()) {
						CommonCriteria criteria = new CommonCriteria();
						criteria.addEq("productId", extend.getCampaignTypeExtension());
						List<SpecificationInventory> inventories = productService.getSpecificationInventory(criteria);
						if (null != inventories && inventories.size() != 0) {
							int sum = inventories.get(0).getAvailableInventory() + inventories.get(0).getCancelInventory()
									- inventories.get(0).getSoldInventory();
							if (sum <= 0) {
								// User user = userService.get(campaign.getModifyUser());
								objs = new HashMap<Object, Object>();
								objs.put("campaign", campaign);
								objs.put("basehref", ServerValue.getMidHostname());
								// objs.put("user", user);
								// logger.info("usr:{}", user.getEmail());
								Mail mail = templateService.formatToMail("mkt.giftRunoutMail", objs);
								mail.setTo("mkt_event@yaodian100.com");
								mail.setSubject("活动赠品缺货通知： " + campaign.getCampaignName());
								mailService.save(mail);
							}
						}
					}
				}
			}
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.campaign.service.CampaignService#chkScmPresentAndSendCampaignEmail(java.lang.String)
	 */
	@Override
	@Transactional(readOnly = false)
	public boolean chkScmPresentAndSendCampaignEmail(String domainName) throws CoreException {
		try {
			Menu systemValueMenu = menuService.get("SystemValue");
			CommonCriteria crit = new CommonCriteria();
			Date now = DateUtil.getCurrentTime();
			crit.addEq("delete", false);
			crit.addEq("enable", true);
			crit.addEq("type", Campaign.Type.C03);
			crit.addIn("range", Arrays.asList(Campaign.Range.Category, Campaign.Range.Product));
			crit.addEq("domain", domainName);
			crit.addLe("startDateTime", now);
			crit.addGe("endDateTime", now);
			List<Campaign> campaigns = getList(0, -1, crit, null);
			CommonCriteria critProd = null;
			List<Product> noneActiveProduct = null;
			List<Product> nonePresentProduct = null;
			List<String> campaignCategoryOffShelves = null;
			List<Product> campaignProductOffShelves = null;
			List<Product> presentProductOffShelves = null;
			for (Campaign campaign : campaigns) {
				noneActiveProduct = new ArrayList<Product>();
				nonePresentProduct = new ArrayList<Product>();
				campaignProductOffShelves = new ArrayList<Product>();
				campaignCategoryOffShelves = new ArrayList<String>();
				presentProductOffShelves = new ArrayList<Product>();
				if (Campaign.Range.Category.equals(campaign.getRange())) {// 分類
					if (campaign.getRangeExtList().size() > 0) {
						for (String categoryId : campaign.getRangeExtList()) {
							Category category = categoryService.getAvailableCategoryNonePermission(Long.parseLong(categoryId));
							if (null == category) {
								campaignCategoryOffShelves.add(categoryId);// 分类不存在或已下架或已过期
							} else {
								critProd = new CommonCriteria();
								critProd.addRlike("mainCategoryPath", category.getCategoryPath());
								critProd.addEq("isScm", "Y");
								critProd.addEq("isDelete", "N");
								critProd.addNe("viewShelf", null);
								noneActiveProduct = productService.getList(0, -1, critProd, null);
							}
						}
					}
				} else if (Campaign.Range.Product.equals(campaign.getRange())) {// 商品
					if (campaign.getRangeExtList().size() > 0) {
						for (String productId : campaign.getRangeExtList()) {
							Product product = productService.get(productId);
							if (null != product) {
								if ("Y".equalsIgnoreCase(product.getIsDelete()) || null == product.getViewShelf()) {
									campaignProductOffShelves.add(product);
								} else if ("Y".equalsIgnoreCase(product.getIsScm())) {
									noneActiveProduct.add(product);
								}
							}
						}
					}
				}
				for (CampaignExtend extend : campaign.getTypeExtends()) {
					Product product = (Product) baseMgr.get(Product.class, extend.getCampaignTypeExtension());
					if (null != product) {
						if ("Y".equalsIgnoreCase(product.getIsDelete())) {
							presentProductOffShelves.add(product);
						} else if ("Y".equalsIgnoreCase(product.getIsScm())) {
							nonePresentProduct.add(product);
						}
					}
				}
				if (campaignCategoryOffShelves.size() > 0 || campaignProductOffShelves.size() > 0
						|| presentProductOffShelves.size() > 0 || noneActiveProduct.size() > 0 || nonePresentProduct.size() > 0) {
					Map<Object, Object> objs = new HashMap<Object, Object>();
					objs.put("contentPath", ServerValue.getMidContextPath());
					objs.put("basehref", ServerValue.getMidHostname());
					objs.put("campaign", campaign);
					objs.put("campaignCategoryOffShelves", campaignCategoryOffShelves);
					objs.put("campaignProductOffShelves", campaignProductOffShelves);
					objs.put("presentProductOffShelves", presentProductOffShelves);
					objs.put("noneActiveProduct", noneActiveProduct);
					objs.put("nonePresentProduct", nonePresentProduct);
					Mail mail = templateService.formatToMail("mkt.chkScmPresentCampaignMail", objs);
					mail.setTo(systemValueMenu.getOptions().get("present_campaign_mail").getMemo1());
					mail.setBcc(systemValueMenu.getOptions().get("present_campaign_bcc_mail").getMemo1());
					mail.setSubject("行销活动赠品检查通知信： " + campaign.getCampaignName());
					mailService.save(mail);
				}
				// logger.info("campaign:{}", campaign);
				// logger.info("campaignCategoryOffShelves:{}", campaignCategoryOffShelves);
				// logger.info("campaignProductOffShelves:{}", campaignProductOffShelves);
				// logger.info("presentProductOffShelves:{}", presentProductOffShelves);
				// logger.info("noneActiveProduct:{}", noneActiveProduct);
				// logger.info("nonePresentProduct:{}", nonePresentProduct);
			}

		} catch (Exception e) {
			logger.info("exception:{}", e.toString());
			return false;
		}
		return true;
	}

	@Override
	@Transactional(readOnly = false)
	public Campaign save(Campaign entity) throws CoreException {
		if (Arrays.asList(Campaign.Type.M01.getCode(), Campaign.Type.M02.getCode(), Campaign.Type.M03.getCode(),
				Campaign.Type.M04.getCode()).contains(entity.getType().getCode())) {
			try {
				JSONObject jsonObject = new JSONObject();
				if (Campaign.Type.M01.getCode().equals(entity.getType().getCode())) {
					jsonObject.put("startPeriod", entity.getStartPeriod());
					jsonObject.put("periodDays", entity.getPeriodDays());
					JSONObject jsonDetailObject = new JSONObject();
					Iterator<CampaignExtend> iter = entity.getTypeExtends().iterator();
					while (iter.hasNext()) {
						CampaignExtend extend = iter.next();
						jsonDetailObject.put("isUpperLimit", extend.isUpperLimit());
						jsonDetailObject.put("bonusLimit", extend.getBonusLimit());
						extend.setJsonDetail(jsonDetailObject.toString());
					}
				}
				if (Campaign.Type.M02.getCode().equals(entity.getType().getCode())) {
					jsonObject.put("offsetRate", entity.getOffsetRate());
					jsonObject.put("offsetUpperLimit", entity.getOffsetUpperLimit());
					jsonObject.put("offsetDiscountLimit", entity.getOffsetDiscountLimit());
				}
				if (Campaign.Type.M03.getCode().equals(entity.getType().getCode())) {
					jsonObject.put("loginCount", entity.getLoginCount());
					jsonObject.put("giveBonus", entity.getGiveBonus());
				}
				if (Campaign.Type.M04.getCode().equals(entity.getType().getCode())) {
					jsonObject.put("commentFirst3", entity.getCommentFirst3());
					jsonObject.put("commentOthers", entity.getCommentOthers());
					jsonObject.put("startPeriod", entity.getStartPeriod());
					jsonObject.put("periodDays", entity.getPeriodDays());
				}
				entity.setJsonDetail(jsonObject.toString());
			} catch (JSONException e) {
				e.fillInStackTrace();
			}
		}
		return getDao().saveOrUpdate(entity);
	}

	Campaign getActiveBonusCampaignByType(String categoryPath, String productId, Map options, Type type)
			throws CoreException {
		Date now = DateUtil.getCurrentTime();
		CommonCriteria cri = new CommonCriteria();
		cri.addEq("enable", true);
		cri.addGe("endDateTime", now);
		cri.addLe("startDateTime", now);
		cri.addEq("type", type);
		List<Campaign> results = getList(0, -1, cri, new String[] { "startDateTime desc", "modifyDate desc" });
		List<Campaign> lists = getValidCampaignTypeByObj(categoryPath, productId, options, results);
		if (null == lists || lists.size() == 0) {
			return null;
		} else {
			return lists.get(0);
		}
	}

	// List<Campaign> getValidCampaignByType(String categoryPath, String productId, Map options, List<String> campaigns,
	// Type type) throws CoreException {
	// // 若 check = false, 把活动 end date 延迟五分钟由资料库捞取
	// Calendar date = Calendar.getInstance();
	// date.setTime(DateUtil.getCurrentTime());
	// CommonCriteria cri = new CommonCriteria();
	// cri.addIn("uuid", campaigns);
	// cri.addEq("enable", true);
	// cri.addLe("startDateTime", date.getTime());
	// date.add(Calendar.MINUTE, -5);
	// cri.addGe("endDateTime", date.getTime());
	// cri.addEq("type", type);
	// List<Campaign> results = getList(0, -1, cri, new String[] { "startDateTime desc", "modifyDate desc" });
	// return results;
	// }

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.campaign.service.CampaignService#getActiveBonusCampaignByM01(java.util.Map)
	 */
	@Override
	public Campaign getActiveBonusCampaignByM01(Map options) throws CoreException {
		return getActiveBonusCampaignByType("", "", options, Type.M01);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.campaign.service.CampaignService#getActiveBonusCampaignByM02(java.util.Map)
	 */
	@Override
	public Campaign getActiveBonusCampaignByM02(Map options) throws CoreException {
		return getActiveBonusCampaignByType("", "", options, Type.M02);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.campaign.service.CampaignService#getActiveBonusCampaignByM03(java.util.Map)
	 */
	@Override
	public Campaign getActiveBonusCampaignByM03(Map options) throws CoreException {
		return getActiveBonusCampaignByType("", "", options, Type.M03);
	}

	@Override
	public Campaign getActiveBonusCampaignByM04(Map options) throws CoreException {
		Campaign campaign = getActiveBonusCampaignByType("", "", options, Type.M04);
		if (null == campaign) {
			campaign = new Campaign();
			campaign.setCommentFirst3("0");
			campaign.setCommentOthers("0");
			campaign.setStartPeriod("0");
			campaign.setPeriodDays("0");
		}
		return campaign;
	}

}
